#!usr/bin/env python3

"""
第十七章 使用api 
"""

import requests 
import os,pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS,Style
from matplotlib import pyplot as plt 

plt.rc('font',family="SimHei") # 设置字体 使其支持中文 http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.rc 

# requests 包的使用

my_style = LS("#336699",base_style=LCS())

my_style =Style(
    label_font_size=14,
    tooltip_font_size=16,
)

#https://api.github.com/rate_limit 查询剩余请求api参数
lang = "javascript"
url = 'https://api.github.com/search/repositories?q=language:{0}&sort=stars'.format(lang)
rootUrl = os.path.dirname(__file__)
saveUrl = os.path.join(rootUrl,"{0}_star.svg".format(lang))

respo = requests.get(url)
data = respo.json()
print(respo.status_code)
print('total_count',data['total_count']) #包含所有的Python类项目数
print("items len",len(data['items'])) #返回的项目个数

#print(data['items'][0]) #第一个项目的信息

prj_names = []
stars = []
watchs = []
forks = []
prjs = data['items']

for prj in prjs:
    desc = prj['description']
    if not desc:
        desc = "None desc ..!"
    prj_names.append(prj['name'])
    stars.append({'value':prj['stargazers_count'],'label':desc,'xlink':prj['html_url']}) #xlink 允许鼠标点击跳转
    watchs.append({'value':prj['watchers'],'label':desc,'xlink':prj['html_url']})
    forks.append({'value':prj['forks_count'],'label':desc,'xlink':prj['html_url']}) #label标签会被显示在 tooltip 上面

my_config = pygal.Config() #配置 字体相关的配置已经移动到style属性相关设置
my_config.x_label_rotation = -45
my_config.show_legend = True
my_config.width = 1200


#设置配置 
bar = pygal.Bar(my_config,style=my_style) 

bar.title = "GitHub {0} 项目信息直方图".format(lang)
bar.x_labels = prj_names
#bar.autofmt_xdate()
bar.add("stars",stars)
bar.add("watchs",watchs)
bar.add("forks",forks)

bar.render_to_file(saveUrl)

fig = plt.figure(figsize=(10,6))

plt.plot([item['value'] for item in stars])
plt.xlabel("项目名称") #这里的设置 x 方向的标签通常是只设置一个 字符串 
plt.xticks(rotation=-45) #设置刻度的旋转角度 


plt.show()